package com.zy.mobile.message.push.netty.heartbeat;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.zy.mobile.message.push.netty.heartbeat.protobuf.MessageProto;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;

public class HeartBeatClientHandler extends ChannelHandlerAdapter{
	
	private int courierId;
	
	private ScheduledFuture<?> heartBeat;
	
	public HeartBeatClientHandler(int courierId) {
		// TODO Auto-generated constructor stub
		this.courierId = courierId;
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
		MessageProto.Message message = (MessageProto.Message)msg;
		if(message.getOrderId()==999){
			System.out.println("Receive server response : ["+ msg + "]");
		}
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx,this.courierId),0,2000,TimeUnit.MILLISECONDS);
		super.channelActive(ctx);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
	}
	
	public class HeartBeatTask implements Runnable{
		
		private final ChannelHandlerContext ctx;
		
		private int courierId;
		
		public HeartBeatTask(final ChannelHandlerContext ctx,int courierId) {
			// TODO Auto-generated constructor stub
			this.ctx = ctx;
			this.courierId = courierId;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			MessageProto.Message message = buildMesage();
//			System.out.println("Client send heart beat message to server : -----> "+message.toString());
			ctx.writeAndFlush(message);
		}
		
		public MessageProto.Message buildMesage(){
			MessageProto.Message.Builder builder = MessageProto.Message.newBuilder();
			builder.setType(1);
			builder.setTimeStamp(new Date().getTime());
			builder.setCourierId(this.courierId);
			return builder.build();
		}
	}

}
